package net.openl10n.packaging.document;

import net.openl10n.api.LocaleId;
import net.openl10n.api.document.Content;
import net.openl10n.opc4j.PackagePart;
import net.openl10n.opc4j.exceptions.InvalidFormatException;
import net.openl10n.packaging.AbstractJaxbContentPart;
import net.openl10n.packaging.OpenLocPartContainer;
import net.openl10n.packaging.OpenLocPartFactory;
import net.openl10n.packaging.OpenLocPartFactoryManager;

import com.google.common.collect.ImmutableList;

public class ContentPart extends AbstractJaxbContentPart{
	public static final String CONTENT_TYPE = "application/openl10n.document.content+xml";
	public static final String TARGET_NAME = "/content.xml";
	public static final String RELATIONSHIP_TYPE = "http://schemas.openl10n.net/document/content";

	private Content content;
	
	public static final OpenLocPartFactory<ContentPart> FACTORY = 
		new OpenLocPartFactory<ContentPart>() {
			@Override
			public ContentPart create(OpenLocPartContainer container, PackagePart part, OpenLocPartFactoryManager partFactoryManager) {
				return new ContentPart(container, part, partFactoryManager);
			}

			@Override
			public String getContentType() {
				return CONTENT_TYPE;
			}

			@Override
			public String getRelationshipType() {
				return RELATIONSHIP_TYPE;
			}

			@Override
			public Class<ContentPart> getTargetClass(){
				return ContentPart.class;
			}
			
			@Override
			protected String getPartNamePattern() {
				return TARGET_NAME;
			};
		};
	
	protected ContentPart(OpenLocPartContainer container, PackagePart part, OpenLocPartFactoryManager partFactoryManager){
		super(container, part, partFactoryManager); 
	}

	public ImmutableList<ContentPart> getDocumentParts(){
		return getPartsOfType(ContentPart.class);
	}

	public ImmutableList<ContentTargetPart> getContentTargetParts(){
		return getPartsOfType(ContentTargetPart.class);
	}
	
	public ContentTargetPart addContentTargetPart(LocaleId localeId){
		try{
			ContentTargetPart part = addNewPart(ContentTargetPart.class);
			return part;
		}
		catch(InvalidFormatException e){
			throw new RuntimeException(e);
		}
	}
	
	public ContentPart addDocumentPart(){
		try{
			ContentPart documentPart = addNewPart(ContentPart.class);
			return documentPart;
		}
		catch(InvalidFormatException e){
			throw new RuntimeException(e);
		}
	}
	
	public Content getContent(){
		if(content == null){
			content = loadOrCreateJaxbObject(Content.class);
		}
		return content;
	}
	
	public void setContent(Content content) {
		this.content = content;
	}
	

	@Override
	protected void onClose() {
		if(content != null)
			saveJaxbObject(content);
		super.onClose();
	}
	
}
